const requireDirectory = require('require-directory');
const Router = require('koa-router');
const path = require('path');
const url = require('url');

class InitManager {
  static initCore(app) {
    InitManager.app = app;
    InitManager.loadConfig();
    InitManager.loadHelper();
    InitManager.initLoadRouters();
    InitManager.initStatic();
  }

  static initLoadRouters() {
    const apiDirectory = path.join(__dirname, '../app/api');
    requireDirectory(module, apiDirectory, {
      /*每当requireDirectory加载到一个文件时,都会调用该回调函数*/visit:
      whenLoadModule
    });

    function whenLoadModule(m) {
      if (m instanceof Router) {
        InitManager.app.use(m.routes()).use(m.allowedMethods());
      }
    }
  }

  static loadConfig(env = 'dev') {
    const configPath = path.join(__dirname, `../config/config.${process.env.NODE_ENV || env}.js`);
    global.config = Object.assign({}, require(path.join(__dirname, '../config/config.default.js')), require(configPath));
  }

  static loadHelper() {
    global.helper = {};
    const multer = require('@koa/multer');
    Object.assign(global.helper
      , require('./HttpException')
      , require('./helper')
      //helper.upload
      , {
        upload: multer({
          storage: multer.diskStorage({
            destination: function (req, file, cb) {
              // const pathname = url.parse(req.url).pathname;
              // console.log('pathname:',pathname); // pathname: /v1/upload/upload-single-file
              cb(null, path.join(__dirname, '../app/public/uploads'));
            }
            , filename: function (req, file, cb) {
              // console.log('file:', file);
              /* file: { fieldname: 'file',
                originalname: '59047957_p0 .jpg',
                encoding: '7bit',
                mimetype: 'image/jpeg' }*/
              const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
              const ext = path.extname(file.originalname);
              cb(null, `${path.basename(file.originalname, ext)}-${uniqueSuffix}${ext}`);
            }
          })
        })
      }
      //helper.redis
      , {
        redis: require('./redis')
      })
  }

  static initStatic() {
    InitManager.app.use(require('koa-static')(path.join(__dirname, '../app/public')))
  }
}

module.exports = InitManager;
